package com.user.gamecenter.network.operate;

import android.annotation.SuppressLint;
import android.util.Log;

import com.google.gson.Gson;
import com.user.gamecenter.network.HttpGetResponse;
import com.user.gamecenter.network.HttpInterfaceManager;
import com.user.gamecenter.network.conversion.JsonConverterFactory;
import com.user.gamecenter.network.help.BaseUrl;
import com.user.gamecenter.network.request.BaseRequest;
import com.user.gamecenter.network.response.BaseResponse;
import com.user.gamecenter.network.retrofit.NonStaticRetrofitManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;


/**
 * Created by Administrator on 2017/3/29.
 */

public class CommonPostOperateRequest extends NonStaticRetrofitManager {

    private String TAG = "CommonPostOperateRequest";

    private static class LazyHolder {
        private static final CommonPostOperateRequest INSTANCE = new CommonPostOperateRequest();
    }

    private CommonPostOperateRequest() {
    }

    public static CommonPostOperateRequest instance() {
        return LazyHolder.INSTANCE;
    }


    /**
     * @方法名: 通用post请求
     * @参数：
     * @返回值：
     * @描述:
     * @作者： cms
     * @创建日期 2016/12/8 15:13
     */
    @SuppressLint("LongLogTag")
    public void commonPostRequest(final BaseRequest baseRequest) {

        //缓存值
        // CodeBetweenRunTimeUtil.instance().setStartTime();
        BaseUrl baseUrl = createBaseUrl("http://121.41.12.224:7788/api.php/Test/");
        createOkHttpClient(baseUrl);
        Retrofit retrofit = createRetrofit(JsonConverterFactory.create(), baseUrl);

        //CodeBetweenRunTimeUtil.instance().getBetweenTime();

        retrofit.create(HttpInterfaceManager.class).commonPostRequest(baseRequest.interfaceName(), baseRequest.getMap()).
                subscribeOn(Schedulers.trampoline()).
                observeOn(Schedulers.trampoline()).
                subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(@NonNull Object o) throws Exception {
                        try {
                            Log.d(TAG, "1-------------- =" + o.toString());
                            JSONObject jsonObject = new JSONObject((String) o);
                            int status = jsonObject.getInt("state");
                            if (1 == status) {
                                //成功
                                HttpGetResponse httpResponse = new HttpGetResponse();
                                httpResponse.setSource(jsonObject.getString("data"));
                                Gson gson = new Gson();
                                Object obj;
                                if (httpResponse.getSource().charAt(0) == '{') {
                                    //对象
                                    obj = gson.fromJson(httpResponse.getSource(), baseRequest.getOriginalData().getClass());
                                } else if (httpResponse.getSource().charAt(0) == '[') {
                                    //集合
                                    JSONArray jsonArray = new JSONArray(httpResponse.getSource());
                                    List<Object> objects = new ArrayList<>();
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        objects.add(gson.fromJson(jsonArray.getString(i), baseRequest.getOriginalData().getClass()));
                                    }
                                    obj = objects;
                                } else {
                                    obj = o;
                                }

                                //转换层
                                if (baseRequest.getConversion() != null) {
                                    obj = baseRequest.getConversion().originalConversionResult(obj, baseRequest.getTag());
                                }

                                BaseResponse baseResponse = baseRequest.getResponse();
                                baseResponse.setData(obj);

                                Log.d(TAG, "1---------------- " + Thread.currentThread().getName());
                                EventBus.getDefault().post(baseResponse);
                            } else {
                                //失败
                                String data = jsonObject.getString("data");
                                JSONObject jsonObject1 = new JSONObject(data);
                                String error = URLDecoder.decode(jsonObject1.getString("mes"), "UTF-8");
                                BaseResponse baseResponse = baseRequest.getResponse();
                                baseResponse.setError(error);
                                EventBus.getDefault().post(baseResponse);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        errorInfo(throwable, baseRequest.getResponse());
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {

                    }
                });

    }
}

